package com.android.manghe.box.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.android.base.frame.title.ETitleType;
import com.android.base.frame.view.MVPActivity;
import com.android.base.tools.Glide.GlideHelper;
import com.android.base.tools.ToastUtil;
import com.android.base.view.roundview.RoundLinearLayout;
import com.android.manghe.R;
import com.android.manghe.box.model.BoxGiftModel;
import com.android.manghe.box.model.BoxModel;
import com.android.manghe.box.model.MessageEvent;
import com.android.manghe.box.presenter.PUnpackingReal;
import com.android.manghe.common.model.ShowBoxEvent;
import com.android.manghe.config.Config;
import com.android.manghe.utils.WindowUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.eightbitlab.rxbus.Bus;
import com.tencent.mm.opensdk.utils.Log;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/11/23 15:59
 * desc   : 开出真的产品
 */
public class UnpackingRealActivity extends MVPActivity<PUnpackingReal> {

    private ImageView mImgGift, mImgRealGift, mImgBg;
    private View mView;
    private TextView mTvName, mTvChange, mTvAgain, mTvGoBox, mTvPrice;
    private int mOrderId;
    private MediaPlayer mediaPlayer;
    private int payWay;
    private RoundLinearLayout mLinearLayout;
    private ImageView mImgLevel;
    private  TextView mTvLevel;
    private BoxModel.DataBean mCurrentBox;
    private AnimatorSet animatorSet;

    @Override
    protected ETitleType showToolBarType() {
        return ETitleType.NO_TITLE;
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
//        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.black));
//        StatusBarUtil.darkMode(this, true);
        WindowUtils.hideStatusBar(this);
        mImgGift = findViewById(R.id.id_img_gift);
        mCurrentBox= (BoxModel.DataBean) getIntent().getSerializableExtra("BoxListModel");
        mOrderId = getIntent().getIntExtra("orderId", 0);
        payWay = getIntent().getIntExtra("PayPageWay", 0);
        mImgBg = findViewById(R.id.id_img_bg);
        mImgBg.setScaleX(3f);
        mImgBg.setScaleY(3f);
        animatorSet=new AnimatorSet();
        Glide.with(this)
                .load(mCurrentBox.cover_pic)
                .crossFade()
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        mImgGift.setImageDrawable(resource);
                        startAnimator();
                    }
                });


        mImgGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getP().getBoxOpen(mOrderId);
            }
        });
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mView = findViewById(R.id.id_open_box);
                initView();
                starFreshenAnimation(mImgBg);
                getP().getBoxOpen(mOrderId);
            }
        },100);

    }

    public void startPlay(int rawRes, boolean isLoop) {
        try {
            stopPlay();
            mediaPlayer = MediaPlayer.create(this, rawRes);
            mediaPlayer.setLooping(isLoop);
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopPlay() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                Log.e("MainActivity", "Unpack=======" + "  mediaPlayer.stop()");
                mediaPlayer.release();
                Log.e("MainActivity", "Unpack=======" + "  mediaPlayer.release()");
                mediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void starFreshenAnimation(ImageView imageView) {
        Animation circle_anim = AnimationUtils.loadAnimation(this, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        circle_anim.setInterpolator(interpolator);
        imageView.startAnimation(circle_anim);  //开始动画
    }


    public void updateDate(List<BoxGiftModel.ListBean> model) {
        try {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (UnpackingRealActivity.this.isFinishing()) {
                        return;
                    }
                    startPlay(R.raw.open_box_2, false);
                    animatorSet.cancel();
                    mView.setVisibility(View.VISIBLE);
                    mImgGift.setVisibility(View.GONE);
                    GlideHelper.loadWithHolderErr(mContext, model.get(0).goods_pic, mImgRealGift);
                    mTvName.setText(model.get(0).goods_name);
                    mTvPrice.setText("￥" + model.get(0).goods_price);
                    WindowUtils.setBoxLevel(mContext, mLinearLayout, mImgLevel, mTvLevel, model.get(0).probability_level);
                    //提醒去开盒页面获取开盒纪录
                    EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_OPEN_SUCCESS));
                  //  Bus.INSTANCE.send(new RefreshIndexNoticeEvent());
                }
            }, 2000);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFailureTip(String context) {
        ToastUtil.showLong(this, context);
    }

    private void initView() {
        mImgRealGift = mView.findViewById(R.id.id_img_real_gift);
        mTvName = mView.findViewById(R.id.id_tv_name);
        mTvChange = mView.findViewById(R.id.id_tv_change);
        mTvAgain = mView.findViewById(R.id.id_tv_again);
        mTvGoBox = mView.findViewById(R.id.id_tv_go_box);
        mTvPrice = mView.findViewById(R.id.id_tv_price_value);
        mLinearLayout= mView.findViewById(R.id.id_ly_level);
        mImgLevel = mView.findViewById(R.id.id_img_level);
        mTvLevel= mView.findViewById(R.id.id_tv_level);
        mTvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通转到盒柜页面
                Bus.INSTANCE.send(new ShowBoxEvent());
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_CLOSE_ACTIVITY));
                finish();
            }
        });

        mTvAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_SHOW_ORDER, 1,payWay));
                finish();
            }
        });
        setColorAndEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WindowUtils.hideStatusBar(this);
    }

    private void setColorAndEvent() {
        SpannableStringBuilder style = new SpannableStringBuilder("前往");
        SpannableStringBuilder style2 = new SpannableStringBuilder("盒柜");
        SpannableStringBuilder style3 = new SpannableStringBuilder("，选择申请发货");
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.yellow500));
        setTextClickEvent(style2, 0, style2.length());//start,end
        style2.setSpan(foregroundColorSpan, 0, style2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.append(style2).append(style3);
        mTvGoBox.setMovementMethod(LinkMovementMethod.getInstance());
        mTvGoBox.setText(style);
    }

    private void setTextClickEvent(SpannableStringBuilder style, int start, int end) {
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //跳转到盒柜页面
                Bus.INSTANCE.send(new ShowBoxEvent());
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_CLOSE_ACTIVITY));
                finish();

            }
        };
        style.setSpan(clickableSpan1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


    /**
     * 开启动画
     */
    private void startAnimator() {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mImgGift, "scaleX", 1f, 1.2f, 1f);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mImgGift, "scaleY", 1f, 1.2f, 1f);
        animatorX.setRepeatCount(ValueAnimator.INFINITE);
        animatorY.setRepeatCount(ValueAnimator.INFINITE);
        animatorSet.setDuration(700);
        animatorSet.play(animatorX).with(animatorY);
        animatorSet.start();
        startPlay(R.raw.open_box_1, true);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_real_unpacking;
    }

    @Override
    public void onBackPressed() {
        stopPlay();
        mImgBg.clearAnimation();
        animatorSet.cancel();
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
        mImgBg.clearAnimation();
        animatorSet.cancel();
    }

}
